// pages/livePlayer/index.ts
const app = getApp();
let config = require("../../utils/config");
let utils = require("../../utils/util.js");
import { http } from "../../utils/request";
//import { SocketTask } from "../../utils/websocket";
let player = null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    topHeight: 0,
    menuBtnHeight: 0,
    po: "",//房间编号
    userRole: null, //用户身份
    roomInfo: null, //直播详情
    roomExtend: null,
    liveStatus: 20, //直播状态 默认20 //10未开始，20直播中，30已结束 40已暂停, 99已禁用
    noticeList: [1], //系统通知
    chatMsgTop: 0,
    chatMsgList: [], //聊天消息
    inputShow: false, //控制输入框显示
    isFocus: false, //聊天框获取焦点
    noChat: true, //是否禁言
    inputVal: "", //聊天内容
    inputHeight: 0, //软键盘的高度

    startTimer: null, //直播开始倒计时器
    surplusTime: 0, //距开始直播剩余的时间秒数
    timeArr: [0,0,0,0],  //倒计时数组[天，时，分，秒]
    showShare: false, //分享弹窗
    showRank: false, //邀请榜弹窗
    rankingList: [], //排行榜列表
    rankingMe: null,  //本人邀约信息
    showPacket: false, //红包
    showAsk: false,//问答题
    answerKey: "", //问题答案
    answerInfo: null,//题目信息
    seeTotal: 0, //观看总时长
    redTimer: null, //领红包倒计时器
    robAward: null, //抢到的红包金额，或者积分数

    inviteCode: "", //邀请码
    online: 0, //在线人数
    laudNum: 0, //点赞总数
    laudCurrent: 0, //点赞控制active的
    isRotate: false,  //视频横竖选择
    playStatus: false, //拉流：网络接收到首个视频数据包（为解决开始推流，到显示画面之间的短暂黑屏）

    isLiveExam: false, //是否参与过活动
    playUrl: "",  //拉流地址
    usePlayUrl: "",
  },
 
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(e) {
    wx.hideShareMenu(); //禁止右上角原生转发
    wx.setNavigationBarColor({
      backgroundColor: '#ff0000',
      frontColor: '#ffffff',
    })
    this.setData({
      po: e.po,
      playUrl: e.pull,
      usePlayUrl: e.pull,
      inviteCode: e.invite?e.invite:"",
      topHeight: wx.getMenuButtonBoundingClientRect().top,
      menuBtnHeight: wx.getMenuButtonBoundingClientRect().height
    })
    
  },

  /**直播详情 */
  queryLiveDetails(){
    let that = this;
    http.requestData("GET","Live/GetRoomItem", {
      PO: this.data.po
    },true).then(res=>{
      if(res.Tag == 10){
        //房间名称最多展示9字
        res.Data.Name = res.Data.Name.length>9?res.Data.Name.substr(0,9)+"...":res.Data.Name;
        res.Data.Cover = res.Data.Cover?config.hostUrl + res.Data.Cover:"/images/default.png"; //封面图
        res.Data.Warm = res.Data.Warm?config.hostUrl + res.Data.Warm:"/images/room/bg-live-room.png"; //暖场背景图
        res.Data.Dvr = res.Data.Dvr?config.playUrl + res.Data.Dvr:""; //回放地址
        that.setData({
          roomInfo: res.Data,
          roomExtend: res.Extend,
          userRole: res.Extend.Manager,
          seeTotal: res.Extend.OnVideo,
          online: res.Extend.OnLine,
          // playUrl: res.Data.Status==20?res.Data.OnPullUrl:"rtmp://127.0.0.1",
          liveStatus: res.Data.Status,
          isLiveExam: res.Extend.IsExam, ////是否已参与过活动
        })
        //直播未开始倒计时
        if(res.Data.Status == 10){
          that.countDownStart(res.Data.Stime);
        }else{
           //非未开始状态，记录进入时间
          that.comeinTimeStore(res.Data.Status);
        }

        /**
         * 店长身份
         * 已参与过活动
         * 活动未开启
         * 活动未设置
         * 活动设置类型：不设置活动
         * **********符合以上任意条件 都不参加活动***********
         */
        if(that.data.userRole || that.data.isLiveExam || res.Data.IsActive==0 || res.Extend.IsSaveActive==0 || res.Extend.IsSaveActive==3){
          console.log("*未达到参会活动条件*")
          return
        }
        that.joinEvent();
      }else{
        http.showToast(res.Message);
      }
    })
  },

  /** 参与活动 判断 */
  joinEvent(){
    //直播中可参与活动
    if(this.data.liveStatus==20){
      //判断累计观看时长 大于 可领取奖励时长   则直接请求领红包（后台判断是否已领取过）
      if(this.data.seeTotal >= this.data.roomExtend.WatchingSee){
        if(this.data.roomInfo.IsExam==1){//设置了答题，查询题目
          this.queryExam();
        }else{
          this.robRedPacket(); //直接抢红包、积分
        }
      }else{
        this.countDownRed();
      }
    }
  },

   /** 邀约人记录保存 */
   saveInvite(){
    let that = this;
    http.requestData("POST","InviteHistory/SaveHistory",{
      po: this.data.po,
      inviteCode: this.data.inviteCode
    }).then(res=>{
      if(res.Tag == 10){
        if(!that.data.userRole){ //普通客户， 先保存邀约信息在查询直播详情
          setTimeout(() => {
            that.queryLiveDetails(); //直播详情
          }, 500);
        }
      }else{
        console.log("保存邀请记录失败")
      }
    })
  },

  /** 直播未开始倒计时 */
  countDownStart(end_time){
    let currentTime = utils.computeTimes(end_time);
    if(currentTime > 0){
      this.data.startTimer = setInterval(() => {
        if(currentTime-- == 0){
          clearInterval(this.data.startTimer);
          this.queryLiveDetails(); //更新详情
          return;
        }
        this.setData({
          surplusTime: currentTime,
          timeArr: utils.countTimes(currentTime)
        }) 
      }, 1000);
    }
  },

  /** 初始连接socket 
  connectSocket(){
    let that = this;
    SocketTask.initWebSocket(config.OPENID(),this.data.po,res=>{
      that.receiveMsg(res);
    })
  },*/

  /** 接收聊天消息 处理 */
  receiveMsg(res){
    console.log("socket 接收消息：",res)
    if(this.data.po != res.po){
      return
    }
    switch (parseInt(res.type)) {
      case 1: //聊天
        this.data.chatMsgList.push(res);
        this.setData({
          chatMsgList: this.data.chatMsgList,
          chatMsgTop: this.data.chatMsgList.length * 20
        })
        break;
      case 4: //在线人数
        this.setData({
          online: res.msg
        })
        break;
      case 5: //点赞
        this.setData({
          laudNum: res.msg
        })
        break;
      case 2: //直播开始推流
        console.log("开始推流")
        this.setData({
          // liveStatus: 20,
          // playUrl: this.data.roomInfo.OnPullUrl
          playUrl: this.data.usePlayUrl
        })
        player.play();
        // this.queryLiveDetails();
        break;
      case 3: //直播停止推流
        console.log("结束推流")
        this.setData({
          liveStatus: 30,
          playStatus: false, //播放状态
          playUrl: "rtmp://127.0.0.1", //更新拉流地址 停止播放
        })
        break;
      case 6: //直播暂停推流
        console.log("暂停推流")
        this.setData({
          liveStatus: 40,
          playStatus: false,
          playUrl: "rtmp://127.0.0.1", //更新拉流地址 停止播放
        })
        break;
      default:
        break;
    }
  },

   /**
   * 直播状态变化事件
   * @param {*} e 
   */
  stateChangeTap(e) {
    console.log('live-player code:', e.detail.code)
    let statusCode = e.detail.code;
    if(statusCode == 2004){ //拉流：网络接收到首个视频数据包并开始播放
      this.setData({
        liveStatus: 20,
        playStatus: true
      })
    }
  },

/**
   * 领取红包计时器
   */
  countDownRed(){
    let that = this;
    this.data.redTimer = setInterval(() => {
      if(that.data.seeTotal++ >= that.data.roomExtend.WatchingSee){
        clearInterval(that.data.redTimer);
        if(that.data.roomInfo.IsExam){//设置答题 并获取题目
          that.queryExam();
        }else{
          that.robRedPacket(); //未设置答题，则直接领取红包
        }
      }
    }, 1000);
  },

  /** 去抽奖 */
  luckDrawTap(){
    return http.showToast("敬请期待")
    http.href("/pages/luckDraw/index?po="+this.data.po);
  },

  /** 抢红包 */
  robPacketTab(){
    // this.setData({
    //   showPacket: true
    // })
    
    if(this.data.seeTotal < this.data.roomExtend.WatchingSee){
      return http.showToast("请继续观看~");
    }
    if(this.data.roomInfo.IsExam==1){ //设置了答题
      this.queryExam();
    }else{
      this.robRedPacket();
    }
  },

  /** 邀请榜 */
  rankingTap(){
    let that = this;
    http.requestData("GET","InviteHistory/GetList",{
      po: this.data.po
    }).then(res=>{
      if(res.Tag==10){
        that.setData({
          rankingList: res.Data,
          rankingMe: res.Extend,
          showRank: true
        })
      }else{
        http.showToast(res.Message)
      }
    })
  },

  /** 转发分享 */
  moreTap(){
    this.setData({
      showRank: false,
      showShare: true
    })
  },

  /** 点赞 */
  laudTap(){
    this.translate();
    http.requestData("GET","Live/Like",{
      po: this.data.po
    }).then(res=>{

    })
  },

  /** 问答题 */
  changeAnswer(e){
    this.setData({
      answerKey: e.currentTarget.dataset.answer
    })
  },

  /** 关闭弹窗 */
  cancelMask(){
    this.setData({
      showShare: false,
      showRank: false,
      showPacket: false,
      showAsk: false
    })
  },

  /** 试题提交答案 */
  confirmAnswer(){
    if(!this.data.answerKey){
      return http.showToast("请选择答案")
    }
    this.cancelMask();
    //答对领红包
    if(this.data.answerKey == this.data.answerInfo.Answer){
      this.robRedPacket() //抢红包
    }else{
      //回答错误  提示谢谢参与
      this.setData({
        showPacket:  true,
        isLiveExam: true
      })
      // http.showToast("sorry,回答错误！");
    }
    //保存答题记录
    let that = this;
    http.requestData("POST", "LiveRoom/SaveExamResult", {
      po: this.data.po,
      examId: this.data.answerInfo.Id, //试题id
      answerResult: this.data.answerKey == this.data.answerInfo.Answer?20:30, //选择的试题答案
      manageId: this.data.inviteCode, //邀请码
      activeType: this.data.answerInfo.IsSaveActive==1?"10":"20" // 活动类型
    }).then(res=>{
      if(res.Tag == 10){
        that.setData({
          isLiveExam: true
        })
      }else{
        console.log("保存答题记录失败")
      }
    })

  },

  /** 抢红包 */
  robRedPacket(){
    let that = this;
    http.requestData("POST","WeChat/WeChatTransfer",{
      po: this.data.po,
      examId: this.data.answerInfo?this.data.answerInfo.Id:""
    }).then(res=>{
      if(res.Tag==10){
        that.setData({
          showPacket:  true,
          isLiveExam: true,
          robAward: {
            type: res.Extend.Type,
            data: res.Data
          }
        })
      }else{
        console.log("领取红包/积分失败")
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    player = wx.createLivePlayerContext('my_player');
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let that = this;
    // if(this.data.fromShare){
    //   app.initCallBack = res => {
    //     if(!config.TEL() || !config.OPENID()){ //未登录
    //       return http.href("/pages/authlogin/index");
    //     }
    //     this.connectSocket();//socket链接
    //     this.queryInviteCode(); //获取店长邀请码
    //     if(config.ROLE() || config.ROLE()=="true"){//店长
    //       setTimeout(() => {
    //         that.queryLiveDetails(); //直播详情
    //       }, 500);
    //     }else{
    //       this.saveInvite(); //非店长，保存邀约人
    //     }
    //   };
    // }else{
    //   this.connectSocket();//socket链接
    //   this.queryInviteCode(); //获取店长邀请码
    //   if(config.ROLE() || config.ROLE()=="true"){//店长
    //     setTimeout(() => {
    //       that.queryLiveDetails(); //直播详情
    //     }, 500);
    //   }else{
    //     this.saveInvite(); //非店长，保存邀约人
    //   }
    // }

    this.setData({
      chatMsgTop: this.data.chatMsgList.length * 20
    })
    //this.connectSocket();//socket链接
    this.queryInviteCode(); //获取店长邀请码

    setTimeout(() => {
      that.queryLiveDetails(); //直播详情
    }, 1000);
    
  },

  /**
   * 去聊天
   */
  bindChatTap(){
    this.setData({
      inputShow: true,
      isFocus: true,
    })
  },

  /**
   * 输入聊天内容
   */
  inputMsg(e){
    this.setData({
      inputVal: e.detail.value
    })
  },
  /**
   * 输入框获取焦点
   * @param {*} e 
   */
  inputFocus(e) {
    this.setData({
      inputHeight: e.detail.height
    })
  },
   /**
   * 输入框失去焦点
   * @param {*} e 
   */
  inputBlur() {
    let that = this;
    setTimeout(() => {
      that.setData({
        inputHeight: 0,
        inputShow: false,
        isFocus: false
      })
    }, 100);
  },
  /**
   * 聊天发送
   */
  sendMsgTap(){
    if(!this.data.inputVal){
      // http.showToast("请输入内容");
      return
    }
    let chatMsg = {
      po: this.data.po, //房间号
      name: config.NICKNAME(),
      mobile: config.TEL(),
      head: config.HEADURL(),
      role: this.data.roomInfo.HostAppletId==config.OPENID()?true:false, //角色 true-主播，false-粉丝（观看者）
      type: 1, //1聊天，2直播商品连接，3点赞
      msg: this.data.inputVal  //消息内容
    }
    // console.log("聊天：",chatMsg)
    //SocketTask.sendMsg(JSON.stringify(chatMsg));
    this.setData({
      inputVal: "" //发送完，消息置空
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    this.leaveTimeStore();//记录离开直播间时间
    clearInterval(this.data.redTimer); //清除红包计时器
    clearInterval(this.data.startTimer); //清除距直播开始倒计时
    //SocketTask.cancelSocket();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.leaveTimeStore();//记录离开直播间时间
    clearInterval(this.data.redTimer); //清除红包计时器
    clearInterval(this.data.startTimer); //清除距直播开始倒计时
    //SocketTask.cancelSocket();
  },

  /** 保存进入直播间的时间 */
  comeinTimeStore(liveStatus){
    http.requestData("POST","Live/StartPlay",{
      po: this.data.po,
      Status: liveStatus
    }).then(res=>{
      if(res.Tag==10){
        console.log("进入直播时间保存成功")
      }
    })
  },
  /** 保存离开直播间的时间 */
  leaveTimeStore(){
    http.requestData("POST","Live/StopPlay",{
      po: this.data.po
    }).then(res=>{
      if(res.Tag==10){
        console.log("离开直播时间保存成功")
      }
    })
  },

  /** 获取问答题目 */
  queryExam(){
    let that = this;
    http.requestData("GET","Live/GetExam",{
      po: this.data.po
    }).then(res=>{
      if(res.Tag==10){
        that.setData({
          showAsk: true,
          answerInfo: res.Data
        })
      }else{
        console.log("活动答题获取失败")
      }
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /** 获取店长邀请码 */
  queryInviteCode(){
    let that = this
    // 获取邀请码
    http.requestData("GET","InviteHistory/GetInvite",{
      po: this.data.po,
      inviteCode: this.data.inviteCode
    }).then(res=>{
      if(res.Tag == 10){
        that.setData({
          inviteCode: res.Data
        })
      }else{
        console.log("获取店长邀请码失败")
      }
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /** 活动设置 */
  activitySetTap(){
    if(this.data.liveStatus == 20){
      return http.showToast("直播中不允许设置活动");
    }
    this.cancelMask();
    http.href("/pages/livePlayer/activitySet/index?po="+this.data.po);
  },
  /** 活动详情 */
  activityInfoTap(){
    http.showToast("暂未开放");
    return;
    this.cancelMask();
    http.href("/pages/livePlayer/activityInfo/index?po="+this.data.po);
  },

  /** 店长没有设置过活动 不允许转发邀请 */
  noShareTap(){
    http.showToast("未设置活动，不允许邀请");
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(e) {
    let that = this;
    this.cancelMask();
    return {
      title: that.data.roomInfo.Name,
      path: "/pages/livePlayer/liveBrief/index?po="+that.data.po + "&invite="+that.data.inviteCode + "&share=ok",
      // path: "/pages/livePlayer/index?po="+that.data.po + "&invite="+that.data.inviteCode + "&share=ok",
      // imageUrl: config.hostUrl + that.data.roomInfo.Cover,
      success(res){
        console.log("分享成功==", res)
      },
      fail(err){
        console.log("分享失败==", err)
      }
    }
  },

  /** 点赞动画 */
  translate() {
    // 随机数 (左右摇摆幅度)
    let randomNum = this.randomNum(-30, 30);
    //laudCurrent是控制active的
    this.setData({
      laudCurrent: parseInt(Math.random()*9)
    })
      // .active 是选择器
    this.animate('.laud-active', [{
        opacity: 1,
        translateY: 0,
        ease:'else',  
        scale: [.5, .5]
      },{
        opacity: 0, //飘到顶部隐藏
        scale: [1, 1],
        translate: [randomNum, -250]
      }], 1500, function () {
      //动画完成后的回调函数
    }.bind(this))
  },
  randomNum(minNum, maxNum) {
    switch (arguments.length) {
      case 1:
        return parseInt(Math.random() * minNum + 1, 10);
        break;
      case 2:
        return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
        // return Math.floor(Math.random()*( maxNum - minNum + 1 ) + minNum );
        break;
      default:
        return 0;
        break;
    }
  },

  /** 横竖屏切换 */
  rotateScreenTap(){
    this.setData({
      isRotate: !this.data.isRotate
    })
  },

  /** 界面返回 */
  gobackTap(){
    wx.switchTab({
      url: '/pages/homepage/index',
    })
    // wx.navigateBack();
  }

})